import datetime
import os
import pandas as pd
import Core.Config as Config
import Core.Gadget as Gadget
from Utility.industry_builder import IndustryBuilder

def rename_suffix(df, fields, suffix, inplace=False):
    rename_field = {}
    for field in fields:
        rename_field[field] = field + "_" + suffix
    df_rename = df.rename(columns=rename_field, inplace=inplace)
    return df_rename


# calc_range_return
# 方便以后搜索到此文件
def calc_industry_range_return(database, datetime1, datetime2, industry_type):
    #
    industry_builder = IndustryBuilder(database, industry_type=industry_type)
    df_industry_mapping = industry_builder.get_industry_mapping()
    df_industry_mapping.rename(columns={industry_type + "_name": "industry_name"}, inplace=True)
    df_industry_mapping.rename(columns={industry_type + "_symbol": "industry_symbol"}, inplace=True)

    # 读取价格收益
    trading_date_t1 = Gadget.find_recent_trading_day(database, datetime1, prev_next="prev")
    df_price_t1 = database.GetDataFrame("financial_data", "index_daily_bar", filter=[("date", trading_date_t1)], projection=["symbol", "close"])
    df_price_t1 = rename_suffix(df_price_t1, fields=["close"], suffix="t1")

    #
    trading_date_t2 = Gadget.find_recent_trading_day(database, datetime2, prev_next="prev")
    df_price_t2 = database.GetDataFrame("financial_data", "index_daily_bar", filter=[("date", trading_date_t2)], projection=["symbol", "close"])
    df_price_t2 = rename_suffix(df_price_t2, fields=["close"], suffix="t2")

    #
    df = pd.merge(df_price_t1, df_price_t2, how="inner", on="symbol")
    df.rename(columns={"symbol": "industry_symbol"}, inplace=True)

    df = pd.merge(df_industry_mapping, df, how="left", on="industry_symbol")
    df["range_return"] = df["close_t2"] / df["close_t1"] - 1

    # print("range return", trading_date_t1, "to", trading_date_t2)
    #
    return df


if __name__ == '__main__':
    # ---Connecting Database---
    path_filename = os.getcwd() + "\..\Config\config_local.json"
    database = Config.create_database(database_type="MySQL", config_file=path_filename, config_field="MySQL")

    #
    datetime1 = datetime.datetime(2023, 1, 1)
    datetime2 = datetime.datetime(2023, 3, 31)
    industry_type = "citics_industry1"
    calc_industry_range_return(database, datetime1, datetime2, industry_type)